// utils/request.js
import store from '@/store'

const BASE_URL = 'http://www.njjinrui.cn:7001' // 替换为你的API基础地址

//const BASE_URL = 'http://192.168.110.20:7001' // 替换为你的API基础地址
const request = (options) => {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token') || store.state.user.token

    let header = {
      'Content-Type': 'application/json',
      ...options.header
    }

    if (token) {
      header['Authorization'] = 'Bearer ' + token
    }

    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: header,
      success: (res) => {
        if (res.statusCode === 200) {
          if (res.data.code === 200 || res.data.code === 0) {
            resolve(res.data)
          } else {
            if (res.data.code === 401) {
              uni.navigateTo({
                url: '/pages/login/login'
              })
              uni.removeStorageSync('token')
              store.commit('user/clearToken')
            }
            uni.showToast({
              title: res.data.message || '请求失败',
              icon: 'none'
            })
            reject(res.data)
          }
        } else {
          uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
          })
          reject(res)
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '网络错误，请检查网络连接',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

const http = {
  get: (url, data = {}, header = {}) => {
    return request({ url, method: 'GET', data, header })
  },
  post: (url, data = {}, header = {}) => {
    return request({ url, method: 'POST', data, header })
  },
  put: (url, data = {}, header = {}) => {
    return request({ url, method: 'PUT', data, header })
  },
  delete: (url, data = {}, header = {}) => {
    return request({ url, method: 'DELETE', data, header })
  }
}

export default http